const isMobile = require('../../common/utils/isMobile.js').isMobile
const App = getApp()
const { API, Ubt, imageHash, User } = App.services
var sliderWidth = 100; // 需要设置slider的宽度，用于计算中间位置

let timer
let secondsCount = 30
const voiceTypes = ['mobile_voice_first', 'mobile_voice_review', 'mobile_register']

Page({
  data: {
    tabs: ["商家用户注册"],
    isAgree: false,

    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    vertificationStatus: 'idle',
    validate_token: '',
    phone: '',
    editPhone: true,
    sms: '',
    password: '',
    scene: 'register',
    authType: 'sms',
    successUrl: null,
    authing: false,
    remainSeconds: 30,
    pageInited: false,
    wechatCode: '',
    avatarUrl: "../../assets/timg.png",
    logIcon: "../../assets/logIcon.png",
    pwdIcon: "../../assets/pwdIcon.png",
    verifiIcon: "../../assets/verifiIcon.png",
    getSmsCodeBtnTxt: "获取验证码",
    getSmsCodeBtnColor: "#0099FF",
    smsCodeDisabled: false,
    loginBtnTxt: "注册",
    loginBtnBgBgColor: "#0099FF",
    btnLoading: false,
    disabled: false
  },
  onLoad: function ({successUrl, scene, type, phone, cartId, sig}) {
    type = voiceTypes.indexOf(type) === -1 ? 'sms' : 'voice'
    this.setData({
      successUrl: successUrl || false,
      scene: scene || 'register',
      authType: type || 'sms',
      phone: phone || '',
      editPhone: phone ? false : true,
      sig: sig || false,
    })

    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });

    if (phone) {
      if (this.data.isVoice) {
        this.sendCode()
      } else {
        this.setData({ authing: false })
        secondsCount = 30
        this.countDown()
      }
      this.setData({ pageInited: true })
    }
  },

  onShow() {
    var _this = this
    wx.login({
      success: function(res) {
        if (res.code) {
          //发起网络请求
          _this.setData({
            wechatCode: res.code
          })
        } else {
          wx.showToast({ title: '请允许打开您的微信授权，否则无法正常' })
        }
      }
    })
  },
  //同意协议
  bindAgreeChange: function (e) {
    this.setData({
      isAgree: !!e.detail.value.length
    });
  },

  //如没有openId,则获取openId，获取失败则退出
  successRedirectBymini(mobile) {
    this.setData({ pageInited: true })
    wx.redirectTo({ url: '/pages/gongzhonghao/index?mobile=' + mobile })
  },

  successRedirect() {
    this.setData({ pageInited: true })
    wx.switchTab({ url: '/pages/retailer/order/order' })
  },
  //手机号输入
  bindPhoneInput(e) {
    this.setData({ phone: e.detail.value })
  },
  //验证码输入
  bindSMSInput(e) {
    this.setData({ sms: e.detail.value })
  },
  //密码输入
  bindPasswordInput(e) {
    this.setData({ password: e.detail.value })
  },
  //验证手机号
  validatePhone() {
    if (!this.data.phone) {
      wx.showToast({ title: '请填写手机号' })
      return false
    } else if (!isMobile(this.data.phone)) {
      wx.showToast({ title: '请填写正确手机号' })
      return false
    }
    return true
  },
  //提示方法
  alertModal(content = '') {
    wx.showModal({
      title: '提示',
      showCancel: false,
      content,
    })
  },
  //发送短信验证码
  sendCode(e) {
    wx.setNavigationBarTitle({ title: '验证手机号' })
    this.getSmsCode()
  },

  sendSMS(e) {
    const phoneValidated = this.validatePhone()
    if (!phoneValidated) return
    this.setData({
      authing: false,
      getSmsCodeBtnColor: "#999",
      smsCodeDisabled: true })
    secondsCount = 30

    API.smsCode({
      mobile: this.data.phone,
    })
        .catch(res => {
          wx.hideToast()
          this.alertModal(res.data.message)
          this.setData({ authing: false })
        })
    this.countDown()
  },

  getSmsCode(e) {
    var that = this;
    var count = 30;
    const phoneValidated = this.validatePhone()
    if (!phoneValidated) return
    //发送短信码
    API.smsCode({
      mobile: this.data.phone,
    }).catch(res => {
      wx.hideToast()
      this.alertModal(res.data.message)
      this.setData({ authing: false })
    })

    var si = setInterval(function () {
      if (count > 0) {
        count--;
        that.setData({
          authing: false,
          getSmsCodeBtnTxt: '已发送'+count + ' s',
          getSmsCodeBtnColor: "#999",
          smsCodeDisabled: true
        });
      } else {
        that.setData({
          getSmsCodeBtnTxt: "获取验证码",
          getSmsCodeBtnColor: "#ff9900",
          smsCodeDisabled: false
        });
        count = 60;
        clearInterval(si);
      }
    }, 1000);

  },

  countDown(e) {
    this.setData({ vertificationStatus: 'sent' })
    timer = setTimeout(() => {
      if (secondsCount > 0) {
        secondsCount = secondsCount - 1
        this.setData({ remainSeconds: secondsCount })
        return this.countDown()
      } else {
        this.setData({
          vertificationStatus: 'retrieve',
          remainSeconds: 30
        })
      }
    }, 1000)
  },

  // 使用验证码登录
  formSubmitV(e) {
    if(!this.validatePhone()) return

    if (!this.data.password.trim()) {
      return wx.showToast({ title: '请填写密码' })
    }

    if (!this.data.sms.trim()) {
      return wx.showToast({ title: '请填写验证码' })
    }

    // if (!this.data.isAgree) {
    //   return wx.showToast({ title: '请阅读《协议》'})
    // }

    if (!this.data.wechatCode.trim()) {
      return wx.showToast({ title: '请对微信授权' })
    }

    wx.showToast({
      title: '正在注册',
      icon: 'loading',
      duration: 10000
    })

    this.setData({ authing: true })
    var _this = this
    //注册操作
    API.register({ mobile: this.data.phone.trim(),
      password: this.data.password.trim(), mobileCode: this.data.sms.trim(),wechatCode:this.data.wechatCode })
        .then( res =>  {
          if (res.data.status === 'success') {
            wx.setStorageSync('USER', res.data.result)
            wx.switchTab({
              url:'/pages/home/index'
            })
            wx.hideToast()
          } else {
            wx.hideToast()
            this.setData({ authing: false })
            wx.showModal({
              content: "注册失败：" + res.data.errorMsg,
              showCancel: false,
              success: function (ress) {
                if (ress.confirm) {
                  console.log('用户点击确定')
                }
              }
            });
          }
        })
        .catch(res => {
          this.alertModal("注册异常，请重试！")
          wx.hideToast()
          this.setData({ authing: false })
        })
  },
  argeeYx:function () {
    wx.downloadFile({
      url: 'https://retailer.citizenroo.com/deliyYx.doc',
      success: function (res) {
        var filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          success: function (res) {

            console.log('打开文档成功')
          }
        })
      }
    })
  }
})
